﻿using System;
using System.Collections.ObjectModel;
using TaskHub.LocalStorage;
using TaskHub.EntityDataModel;
using System.Linq;

namespace TaskHub.Controller
{
    public class ApplicationDataController
    {
        public ObservableCollection<ItemViewModel> MyTasks { get; set; }
        public ObservableCollection<ItemViewModel> OtherTasks { get; set; }
        public ObservableCollection<ItemViewModel> Contacts { get; set; }


        public ApplicationDataController()
        {
            IsolatedStorageDAO.InitStorage();
            var tasks = IsolatedStorageDAO.GetMyTasks();
            var otherTasks = IsolatedStorageDAO.GetOtherTasks();
            var contacts = IsolatedStorageDAO.GetContacts();          

            MyTasks = ConvertToTaskView(tasks);
            OtherTasks = ConvertToTaskView(otherTasks);
            Contacts = ConvertToContactView(contacts);
            
        }

        private ObservableCollection<ItemViewModel> ConvertToContactView(System.Collections.Generic.IList<EntityDataModel.ContactEDM> contacts)
        {
            var collection = new ObservableCollection<ItemViewModel>();

            if (contacts != null && contacts.Count > 0)
            {
                foreach (var item in contacts)
                {
                    collection.Add(new ItemViewModel()
                    {
                        LineOne = item.ContactAccountId.ToString(),
                        LineTwo = item.Name
                    });
                }               
            }
            return collection;
        }

        private ObservableCollection<ItemViewModel> ConvertToTaskView(System.Collections.Generic.IList<EntityDataModel.TaskEDM> tasks)
        {
            var collection = new ObservableCollection<ItemViewModel>();

            if (tasks != null && tasks.Count > 0)
            {
                foreach (var item in tasks)
                {
                    collection.Add(new ItemViewModel()
                              {
                                  LineOne = item.Description,
                                  LineTwo = item.ObservationText,
                                  LineThree = item.DueDate.ToShortDateString()
                              });
                }                
            }
            return collection;
        }
    }       
}
